package com.hwc;

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class NGuessNumber {
    private static final Scanner scanner = new Scanner(System.in);

    public static int []  generateAnswer () {
        Random r = new Random();
        int [] numbers= new int[4];
        int i=0;
        ArrayList<Integer> arrayList=new ArrayList<>();
        while (arrayList.size() !=4){
            int answer = r.nextInt(10);
            if(!arrayList.contains(answer)){
                arrayList.add(answer);
                numbers[i]=answer;
                i++;
            }
        }
        return  numbers;
    }
    public  static int[] getPlayerInput(){
        System.out.println("游戏玩法：根据提示，猜对4个数字和它们的顺序即可获胜！");
        System.out.println("请输入4个0-9之间的数字");
        int []inputResult = new int[4];
        for (int i = 0; i < 4; i++) {
            int input = scanner.nextInt();
            inputResult[i] = input;
        }

return  inputResult;
    }
    public static int[] compareGuessAnswer(int[] answers, int[] inputs) {
        int A = 0, B = 0;
        for (int index = 0; index < answers.length; index++) {
            int answer = answers[index];
            if (inputs[index] == answer) {
                A++;
            } else {
                for (int i = 0; i < answers.length; i++) {
                    if (i == index) continue;
                    if (inputs[i] == answer) {
                        B++;
                        break;
                    }
                }
            }
        }

        String tip = "您输入的数字是：\n";
        for (int i : inputs) {
            tip += i;
            tip += " ";
        }
        System.out.println(tip);
        System.out.println(A + " " + "A" + " " + B + " " + "B");
        return new int[] { A, B };
    }
    // A为4时，即获胜
    public static boolean isWin(int A) {
        return A == 4;
    }

    public static void main(String[] args) {
        do {
            int[] answers = generateAnswer();
            while (!isWin(compareGuessAnswer(answers, getPlayerInput())[0])) {
                System.out.println("A表示存在且位置正确的数字个数，B表示存在但位置不正确的数字个数。");
                System.out.println("如1A2B，代表你猜测的4个数字中有3个是正确的，有一个位置正确，2个位置不正确。");
            }
            System.out.println("恭喜你猜对了，游戏结束！");
            System.out.println("是否开启新一轮游戏？ (y/n)");
        } while (scanner.next().equalsIgnoreCase("y"));
    }


}
